<template>
    <el-card style="width: 80%; margin-left: 10% ; margin-top: 20px">
      <el-descriptions title="个人信息简介" border>
        <template #extra>
          <el-button type="primary" @click="updateCustomerInfo">完善信息</el-button>
        </template>
        <el-descriptions-item
            :rowspan="2"
            :width="140"
            label="头像"
            align="center"
        >

          <el-image
              style="width: 100px; height: 100px"
              src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"/>
        </el-descriptions-item>
        <el-descriptions-item label="公司名称" align="center">{{customerInfo.customerName}}</el-descriptions-item>
        <el-descriptions-item label="联系电话" align="center">{{customerInfo.contactInfo}}</el-descriptions-item>
        <el-descriptions-item label="实名信息" align="center">{{customerInfo.realNameId}}</el-descriptions-item>
        <el-descriptions-item  label="业务类型" align="center" >
          <el-tag size="small"  v-if="isDataLoaded" >{{getBusinessType(customerInfo.businessType)}}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="公司邮箱" align="center">
          {{ customerInfo.customerEmail }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card> <!-- 添加了结束标签 -->

  <el-card style="width: 80%; margin-left: 10% ; margin-top: 20px">
    <el-descriptions title="地址信息" border>
      <template #extra>
        <el-button style="margin-left: 30px" type="primary"  @click="addCustomerAddr">新增地址</el-button>


      </template>
    </el-descriptions>
    <div>
      <el-table :data="customerAddr" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="consignee" label="收货人" width="120" align="center"></el-table-column>
        <el-table-column prop="phone" label="联系电话" width="200"  align="center"></el-table-column>
        <el-table-column prop="zipcode" label="邮政编码" width="200"  align="center"></el-table-column>
        <el-table-column label="地址" width="350"  align="center">
          <template  #default="scope">
            {{ scope.row.state + ' - ' + scope.row.city + ' - ' + scope.row.district }}
          </template>
        </el-table-column>
        <el-table-column prop="streetAddress" label="详细地址" width="250"  align="center"></el-table-column>
        <el-table-column prop="storeName" label="店铺名称" width="250"  align="center"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="editcustomerAddr(scope.row)"
                       v-hasPermi="['system:order:remove']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="deletecustomerAddr(scope.row)"
                       v-hasPermi="['system:order:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-card>

  <el-dialog
      title="修改个人信息"
      v-model="infodialogVisible"
      width="50%"
      :before-close="handleClose">
    <el-form :model="infoform"
             :rules="editRules"
             ref="infoFormRef"
             label-width="150px">

      <el-form-item label="公司名称：">
        <el-input v-model="infoform.customerName"placeholder="请输入公司名称" style="width: 400px"></el-input>
      </el-form-item>
      <el-form-item label="联系电话：">
        <el-input v-model="infoform.contactInfo" style="width: 400px"placeholder="请输入联系电话">
        </el-input>
      </el-form-item>
      <el-form-item label="公司邮箱：">
        <el-input v-model="infoform.customerEmail" style="width: 400px"placeholder="请输入公司邮箱">
        </el-input>
      </el-form-item>
      <el-form-item label="业务类型：">
        <el-select v-model="infoform.businessType" placeholder="请选择业务类型">
          <el-option
              v-for="item in businessType"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="实名信息：">
        <el-input v-model="infoform.realNameId" type="textarea" rows="3"placeholder="请输入实名信息">
        </el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer" style="margin-left: 40%">
        <el-button @click="infodialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handlAddInfo">确 定</el-button>
      </span>
  </el-dialog>




  <el-dialog title="新增地址信息"
             v-model="addrDialogVisible"
             width="50%">
    <el-form :model="addform"
             ref="addrFormRef"
             :rules="addrRules"
             label-width="150px">

      <el-form-item label="收货人姓名：" prop="consignee">
        <el-input v-model="addform.consignee"placeholder="请输入收货人姓名" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="手机号码：" prop="phone">
        <el-input v-model="addform.phone" style="width: 200px"placeholder="请输入手机号码">
        </el-input>
      </el-form-item>
      <el-form-item label="邮政编码：" prop="zipcode">
        <el-input v-model="addform.zipcode" style="width: 200px"placeholder="请输入邮政编码">
        </el-input>
      </el-form-item>
      <el-form-item label="所在区域："placeholder="请选择所在区域" prop="addOptions" >
        <el-cascader
            v-model="addOptions"
            :options="options"
            @change="handleChange"
            clearable
            style="width: 300px;"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="详细地址：" prop="streetAddress">
        <el-input v-model="addform.streetAddress" type="textarea" rows="3"placeholder="请输入详细地址">
        </el-input>
      </el-form-item>
      <el-form-item label="店铺名称：" prop="storeName">
        <el-input v-model="addform.storeName" type="textarea" rows="3"placeholder="请输入店铺名称">
        </el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer" style="margin-left: 40%">
        <el-button @click="addrDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handlAddAddr">确 定</el-button>
      </span>
  </el-dialog>


  <el-dialog title="修改地址信息"
             v-model="editDialogVisible"
             width="50%">
    <el-form :model="editform"
             :rules="addrRules"
             ref="receiverInfoForm"
             label-width="150px">

      <el-form-item label="收货人姓名：" prop="consignee">
        <el-input v-model="editform.consignee"placeholder="请输入收货人姓名" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="手机号码：" prop="phone">
        <el-input v-model="editform.phone" style="width: 200px"placeholder="请输入手机号码" >
        </el-input>
      </el-form-item>
      <el-form-item label="邮政编码：" prop="zipcode">
        <el-input v-model="editform.zipcode" style="width: 200px"placeholder="请输入邮政编码">
        </el-input>
      </el-form-item>
      <el-form-item label="所在区域："placeholder="请选择所在区域">
        <el-cascader
            v-model="editOptions"
            :options="options"
            @change="handleChange"
            clearable
            style="width: 300px;"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="详细地址：" prop="streetAddress">
        <el-input v-model="editform.streetAddress" type="textarea" rows="3"placeholder="请输入详细地址">
        </el-input>
      </el-form-item>
      <el-form-item label="店铺名称：" prop="storeName">
        <el-input v-model="editform.storeName" type="textarea" rows="3"placeholder="请输入店铺名称">
        </el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer" style="margin-left: 40%">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handlUpdateInfo">确 定</el-button>
      </span>
  </el-dialog>


</template>

<script>
import {getInfo, updateInfo} from "@/api/system/info.js";
import {addAddr, delCustomerAddr, listAddr, updateAddr} from "@/api/system/addr.js";
import useUserStore from '@/store/modules/user'
import {getDicts} from "@/api/system/dict/data.js";
import * as areaData from "element-china-area-data";

const userStore = useUserStore()

export default {
  name: "Info",
  data() {
    return {
      customerId: userStore.id,
      customerInfo: {},
      customerAddr: [],
      paymentMeth:{},
      businessType:{},

      editform:{},
      editOptions:{},
      addform:{},
      addOptions:{},
      infoform:{},



      isDataLoaded:false,
      addrDialogVisible:false,
      editDialogVisible:false,
      infodialogVisible:false,
      options:areaData.regionData,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerId: userStore.id,
      },
      total: 0,

      editRules: {
        customerName: [
          { required: true, message: '公司名称不能为空', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在2-50个字符', trigger: 'blur' }
        ],
        contactInfo: [
          { required: true, message: '联系电话不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        customerEmail: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ],
        businessType: [
          { required: true, message: '请选择业务类型', trigger: 'change' }
        ],
        realNameId: [
          { required: true, message: '实名信息不能为空', trigger: 'blur' },
          { pattern: /^\d{17}[\dXx]$/, message: '身份证格式不正确', trigger: 'blur' }
        ]
      },
      addrRules: {
        consignee: [
          { required: true, message: '收货人不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '长度2-20个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        zipcode: [
          { pattern: /^\d{6}$/, message: '需6位数字邮编', trigger: 'blur' }
        ],
        streetAddress: [
          { required: true, message: '详细地址不能为空', trigger: 'blur' },
          { min: 5, max: 100, message: '长度5-100个字符', trigger: 'blur' }
        ],
        storeName: [
          { required: true, message: '店铺地址不能为空', trigger: 'blur' },
          { min: 5, max: 100, message: '长度5-100个字符', trigger: 'blur' }
        ],

      }

    };
  },
  mounted() {
    this.loadDict()
    this.getCustomerInfo()
    this.getCustomerAddr()

  },
  methods: {

    handlAddAddr(){

      this.$refs.addrFormRef.validate(valid => {
        if(valid){
          const processData = {
            customerId: this.customerId,
            consignee: this.addform.consignee,
            phone: this.addform.phone,
            zipcode: this.addform.zipcode,
            streetAddress: this.addform.streetAddress,
            country: "中国",
            state: this.codeToText(this.addOptions[0]),
            city: this.codeToText(this.addOptions[1]),
            district: this.codeToText(this.addOptions[2]),
            storeName: this.addform.storeName,
          }
          addAddr(processData).then(response => {
            this.$message.success("新增成功");
            this.addrDialogVisible =false
            this.addform = {}
            this.addOptions = []
            this.getCustomerAddr()
          })
        }
      });
    },

    handlUpdateInfo(){
      this.$refs.receiverInfoForm.validate(valid => {
        if(valid){
          const processData = {
            customerId: this.customerId,
            addressId: this.editform.addressId,
            consignee: this.editform.consignee,
            phone: this.editform.phone,
            zipcode: this.editform.zipcode,
            streetAddress: this.editform.streetAddress,
            country: "中国",
            state: this.codeToText(this.editOptions[0]),
            city: this.codeToText(this.editOptions[1]),
            district: this.codeToText(this.editOptions[2]),
            storeName: this.editform.storeName,
          }
          updateAddr(processData).then(response => {
            this.$message.success("修改成功");
            this.editDialogVisible = false
            this.getCustomerAddr()
          })
        }
      });

    },

    handlAddInfo(){
      this.$refs.infoFormRef.validate(valid => {
        if (valid) {
          updateInfo(this.infoform).then(response => {
            this.$message.success("修改成功");
            this.getCustomerInfo()
            this.infodialogVisible = false
          });
        }
      })

    },

    deletecustomerAddr(row){

      this.$confirm('确定删除该地址吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        const customerAddr = {
          customerId: this.customerId,
          addressId: row.addressId
        }
        delCustomerAddr(customerAddr).then(response => {
          this.$message.success("删除成功");
          this.getCustomerAddr()
        })

      })

    },


    updateCustomerInfo(){
      Object.assign(this.infoform, this.customerInfo)
      this.infodialogVisible = true;
    },

    addCustomerAddr(){
      this.addrDialogVisible = true
    },

    editcustomerAddr(row){
      Object.assign(this.editform, row)
      this.editOptions = this.namesToCodes([this.editform.state,this.editform.city,this.editform.district])
      this.editDialogVisible = true

    },

    getCustomerAddr(){
      listAddr(this.queryParams).then(response => {
        this.total = response.total;
        this.customerAddr = response.rows;
        console.log('customerAddr',this.customerAddr)
      })
    },

    getCustomerInfo(){
      getInfo(this.customerId).then(response => {
        this.customerInfo = response.data;
        console.log('customerInfo',this.customerInfo)
      }).catch(error => {
        console.error('获取客户信息失败:', error);
      });
    },

    loadDict(){

      getDicts("business_type").then(response =>{
        this.businessType =response.data
        this.isDataLoaded = true;
        console.log(this.businessType)
      })

    },
    getBusinessType(value){

      return this.businessType[parseInt(this.customerInfo.businessType)-1].dictLabel
    },
    codeToText(code) {
      const find = (data, code) => {
        for (let key in data) {
          if (data[key].value === code) {
            return data[key].label;
          }
          if (data[key].children) {
            const result = find(data[key].children, code);
            if (result) return result;
          }
        }
        return null;
      };

      return find(areaData.regionData, code);
    },

    namesToCodes(names) {
      let codes = [];
      let currentData = areaData.regionData;
      names.forEach(name => {
        let found = false;
        for (let key in currentData) {
          if (currentData[key].label === name) {
            codes.push(currentData[key].value);
            if (currentData[key].children) {
              currentData = currentData[key].children;
              found = true;
              break;
            } else {
              found = true;
              break;
            }
          }
        }
        if (!found) {
          console.warn(`Could not find the area with name: ${name}`);
          return [];
        }
      });
      return codes;
    },


  },
};
</script>

<style scoped>
.img {
  width: 80px;
  height: 80px;
}
/* 添加错误提示对齐 */
.el-form-item__error {
  margin-left: 150px;
  padding-top: 4px;
}
/* 高亮错误输入框 */
.el-input.is-error .el-input__inner {
  border-color: #ff4949;
  background-color: #fff8f8;
}
</style>
